package com.karrim.client.widget.file;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.DivElement;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;

/**
 *
 * @author andrea.cantafio
 */
public class FileWidget extends Composite {

    private static FileWidgetUiBinder uiBinder = GWT.create(FileWidgetUiBinder.class);

    interface FileWidgetUiBinder extends UiBinder<Widget, FileWidget> {
    }

    public FileWidget() {
        initWidget(uiBinder.createAndBindUi(this));
        
        btnAddInput.addClickHandler(new ClickHandler() {

            public void onClick(ClickEvent event) {
                FileUpload upload = new FileUpload();
                upload.setName(DEFAULT_INPUT_NAME + fileCount++);
                RootPanel inputHolder = RootPanel.get("inputHolder");
                inputHolder.add(new HTML("<br />"));
                inputHolder.add(upload);
            }
        });
        btnAddInput.click();
        
        formPanel.setAction(GWT.getModuleBaseURL() + "file");
        formPanel.setEncoding(FormPanel.ENCODING_MULTIPART);
        formPanel.setMethod(FormPanel.METHOD_POST);
        
        formPanel.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {

            public void onSubmitComplete(SubmitCompleteEvent event) {
                Window.alert("Done!");
            }
        });
        
        pnl.add(formPanel);
    } 
    @UiField
    Button btnAddInput;
    @UiField
    FormPanel formPanel;
    @UiField
    HTMLPanel pnl;
    
    private int fileCount = 0;
    public final String DEFAULT_INPUT_NAME = "userFile";
}
